#include"snakeLinux.h"
#include"gameLinux.c"
#include"userLinux.c"

// 全局变量定义
struct SNAKE snake;
struct FOOD food;
int score = 0;
struct GameState game;
Obstacle obstacles[MAX_OBSTACLES];
int kx = 0;
int ky = 0;
int lastX = 0;
int lastY = 0;
int sleepSecond = 500;
bool isPaused = false;
int obstacleCount = 0;
UserNode *head = NULL;
UserNode* currentUser = NULL;

// 控制台相关函数实现
void hideCursor() {
    printf("\033[?25l");
    fflush(stdout);
}

void showCursor() {
    printf("\033[?25h");
    fflush(stdout);
}

void setCursorPosition(int x, int y) {
    printf("\033[%d;%dH", y+1, x+1);
    fflush(stdout);
}

void clearScreen() {
    printf("\033[2J");
    setCursorPosition(0, 0);
}

// 非阻塞键盘输入
int kbhit() {
    struct termios oldt, newt;
    int ch;
    int oldf;

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

    ch = getchar();

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    fcntl(STDIN_FILENO, F_SETFL, oldf);

    if(ch != EOF) {
        ungetc(ch, stdin);
        return 1;
    }
    return 0;
}

int getch() {
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

// 游戏主函数
int main() {
    srand(time(NULL));
    hideCursor();  // 隐藏光标
    initUserSystem();
    initUser();
    playGame();
    gameOver();

    // 释放用户链表
    while(head != NULL) {
        UserNode* temp = head;
        head = head->next;
        free(temp);
    }
    showCursor();  // 恢复光标
    return 0;
}